const quniuconfig = require("./quniuconfig")
const path = require("path")

function uploadFile(pathname, keyInQiniuCloud, onSuccess, onError) {
    /* 
        pathname:文件的名字，
        keyInQiniuCloud:上传到七牛云的那个路径
        onSuccess:成功的回调
        onError：失败的回调
    */
    var formUploader = new quniuconfig.qiniu.form_up.FormUploader(quniuconfig.config);
    var putExtra = new quniuconfig.qiniu.form_up.PutExtra();
    const randmonKey = Date.now() + "-" + parseInt(Math.random() * 1000) + path.extname(pathname)
    const localFile = path.resolve(process.cwd(), 'uploads', pathname)
    formUploader.putFile(quniuconfig.uploadToken(), keyInQiniuCloud + randmonKey, localFile, putExtra)
        .then(({ data, resp }) => {
            if (resp.statusCode === 200) {
                onSuccess(resp)
            } else {
                onError(resp)
            }
        })
        .catch(err => {
            console.log('failed', err);
        });
}


module.exports = {
    uploadFile
}